import { apiService } from '../../api/apiService';
import wx from 'weixin-js-sdk';
import { getRepairBymanucode, getRepairByphone, getRepairVercode, getRepairByUser, jssdksignature } from '../../api/server';
import { showSuccess } from '../../util/MessageDeal';
import Cookies from 'js-cookie';
import { reactive, onMounted, onBeforeMount } from 'vue';
import { ssm } from '@/util/ServerLang';
import { selfI18n } from '@/i18n';

export function useRepairOrderQuerySetup (props) {
    const username = Cookies.get('username') || '';

    const query_state = reactive({
        phone: '',
        vercode: '',
        manufacturecode: '',
        show_querybyuser: false
    });

    onMounted(() => {
        // 获取扫码权限
        getScanQRCode();
        if (Cookies.get('username')) {
            query_state.show_querybyuser = true;
        }
    });

    const setQueryCookies = (type, ...args) => {
        if (type === 'phone') {
            Cookies.set('setquerytype', 'phone');
            Cookies.set('repairphone', args[0]);
            Cookies.set('queryvercode', args[1]);
        } else if (type === 'manucode') {
            Cookies.set('setquerytype', 'manufacturecode');
            Cookies.set('manufacturecode', args[0]);
        } else {
            Cookies.set('setquerytype', type);
        }
    };

    // 扫一扫获取信息
    const getScanQRCode = () => {
        const param = {};
        if (window.__wxjs_is_wkwebview) {
            param.isios = true;
        }
        apiService({
            api: jssdksignature,
            param: param,
            success: data => {
                wx.config({
                    debug: false,
                    appId: data.values.appId,
                    timestamp: data.values.timestamp,
                    nonceStr: data.values.nonceStr,
                    signature: data.values.signature,
                    jsApiList: [
                        'scanQRCode'
                    ]
                });
            }
        });
    };

    // 调起扫一扫
    const scanCode = (callback) => {
        wx.scanQRCode({
            debug: false,
            needResult: 1, // 默认为0，扫描结果由微信处理，1则直接返回扫描结果，
            scanType: ['qrCode', 'barCode'], // 可以指定扫二维码还是一维码，默认二者都有
            success: (res) => {
                callback(res.resultStr);
            },
            fail: (err) => {
                console.log(err);
            }
        });
    };
    const queryURLParameter = (url) => {
        const obj = {};
        const reg = /([^?&=]+)=([^?&=]+)/g;
        let res = reg.exec(url);
        while (res) {
            obj[res[1]] = res[2];
            res = reg.exec(url);
        }
        return obj;
    };
    const scanManufacturecode = (callback) => {
        // const reg = /^\/\w+\?manufacturecode=(\w+)$/;

        scanCode((result) => {
            const query = queryURLParameter(result);
            if (query) {
                query_state.manufacturecode = query.manufacturecode;
            }
            callback && callback(query.manufacturecode);
        });
    };
    const scanManufacturecodeBack = (callback) => {
        scanManufacturecode(callback);
    };

    const getRepairDataByManucode = (params) => {
        return new Promise((resolve, reject) => {
            apiService({
                api: getRepairBymanucode,
                param: { ...params, username: username },
                success: (data) => {
                    resolve(data);
                },
                fail: (data) => {
                    resolve(data);
                },
                error: (err) => {
                    reject(err);
                }
            });
        });
    };
    const getVercodeForRepair = (param) => {
        apiService({
            api: getRepairVercode,
            param: { ...param },
            success: () => {
                showSuccess(selfI18n('wp_Sent_successfully'));
            }
        });
    };

    return {
        query_state,
        setQueryCookies,
        scanManufacturecode,
        getRepairDataByManucode,
        getVercodeForRepair,
        username,
        scanManufacturecodeBack
    };
}
export function useRepairOrderQueryListSetup () {
    const query_list_sate = reactive({
        querytype: '',
        queryphone: '',
        querymanucode: '',
        queryvercode: '',
        loading: false,
        loadfinish: false,
        listdata: []
    });
    const queryfilter = reactive({

        administrator: '',
        company: '',
        content: '',
        manufacturecode: '',
        n: 20,
        name: '',
        p: 1,
        phone: '',
        repairid: '',
        createtime: '',
        repairtimeend: '',
        repairtimestart: '',
        status: 'all',
        username: '',
        vercode: ''
    });

    onBeforeMount(() => {
        // setQueryListState();
        // loadMorePage();
    });

    const setQueryListState = () => {
        const type = Cookies.get('setquerytype');
        const phone = Cookies.get('repairphone');
        const vercode = Cookies.get('queryvercode');
        const manucode = Cookies.get('manufacturecode');
        query_list_sate.queryvercode = vercode;
        query_list_sate.querytype = type;
        query_list_sate.queryphone = phone;
        query_list_sate.querymanucode = manucode;
    };

    const loadMorePage = () => {
        if (query_list_sate.querytype === 'userphone') {
            getRepairDataByUserPhone({ ...queryfilter }, data => setListData(data));
        }
        if (query_list_sate.querytype === 'phone') {
            getRepairDataByPhone({ ...queryfilter, phone: query_list_sate.queryphone, vercode: query_list_sate.queryvercode }, data => setListData(data));
        } else if (query_list_sate.querytype === 'manufacturecode') {
            getRepairDataByManucode({ ...queryfilter, manufacturecode: query_list_sate.querymanucode }, data => setListData(data));
        }
    };
    const setListData = (data) => {
        queryfilter.p++;
        query_list_sate.listdata = query_list_sate.listdata.concat(data.value);
        if (data.value && data.value.length < queryfilter.n) {
            query_list_sate.loadfinish = true;
        }
    };
    const getRepairDataByManucode = (params, callback) => {
        query_list_sate.loading = true;
        apiService({
            api: getRepairBymanucode,
            param: { ...params },
            success: (data) => {
                callback && callback(data);
            },
            fail: (data) => {
                ssm(data);
                query_list_sate.loadfinish = true;
            },
            error: () => {
                query_list_sate.loadfinish = true;
            },
            end: () => {
                query_list_sate.loading = false;
            }
        });
    };
    const getRepairDataByUserPhone = (params, callback) => {
        query_list_sate.loading = true;
        apiService({
            api: getRepairByUser,
            param: { ...params },
            success: (data) => {
                callback && callback(data);
            },
            fail: (data) => {
                ssm(data);
                query_list_sate.loadfinish = true;
            },
            error: () => {
                query_list_sate.loadfinish = true;
            },
            end: () => {
                query_list_sate.loading = false;
            }
        });
    };
    const getRepairDataByPhone = (params, callback) => {
        query_list_sate.loading = true;
        apiService({
            api: getRepairByphone,
            param: { ...params },
            success: (data) => {
                callback && callback(data);
            },
            fail: (data) => {
                query_list_sate.loadfinish = true;
                ssm(data);
            },
            end: () => {
                query_list_sate.loading = false;
            }
        });
    };

    return {
        loadMorePage,
        setQueryListState,
        query_list_sate,
        getRepairDataByManucode,
        getRepairDataByUserPhone,
        getRepairDataByPhone
    };
}
